/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.uml_generator.gui;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;

import com.genia.toolbox.uml_generator.bean.impl.GenerationConfigurationImpl;
import com.genia.toolbox.uml_generator.manager.UmlGeneratorManager;

/**
 * Main GUI frame.
 */
@SuppressWarnings("serial")
public class MainFrame
    extends JFrame
    implements ActionListener
{

  /**
   * the {@link UmlGeneratorManager} to use.
   */
  private UmlGeneratorManager umlGeneratorManager;

  /**
   * The main panel.
   */
  private FileSelectionPanel mainPanel = null;

  /**
   * The generation button.
   */
  private JButton bGenerate;



  /**
   * Constructor.
   */
  public MainFrame()
  {
    super("UML generator");

    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch (final Exception e) {
      // Do nothing
    }

    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final URL url = loader.getResource("com/genia/toolbox/uml_generator/gui/image/icon.gif");
    this.setIconImage(new ImageIcon(url).getImage());

    final Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    final int widthScreen = dim.getSize().width;
    final int heightScreen = dim.getSize().height;
    final int width = 400;
    final int height = 220;
    this.setBounds(widthScreen / 2 - width / 2, heightScreen / 2 - height / 2, width, height);

    this.addWindowListener(new WindowAdapter()
    {
      @Override
      public void windowClosing(final WindowEvent e)
      {
        System.exit(0);
      }
    });

    final GridBagLayout layout = new GridBagLayout();
    final GridBagConstraints constraints = new GridBagConstraints();
    this.getContentPane().setLayout(layout);

    constraints.gridx = 1;
    constraints.gridy = 1;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.fill = GridBagConstraints.BOTH;
    constraints.insets = new Insets(0, 0, 0, 0);
    this.getContentPane().add(this.createPanel(), constraints);
  }



  /**
   * create a panel.
   * 
   * @return a jpanel.
   */
  public JPanel createPanel()
  {
    final JPanel panel = new JPanel();

    final GridBagLayout layout = new GridBagLayout();
    final GridBagConstraints constraints = new GridBagConstraints();
    panel.setLayout(layout);

    this.mainPanel = new FileSelectionPanel();
    constraints.gridx = 1;
    constraints.gridy = 1;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.fill = GridBagConstraints.BOTH;
    constraints.insets = new Insets(0, 0, 0, 0);
    panel.add(this.mainPanel, constraints);

    this.bGenerate = new JButton("Generate the DAO");
    this.bGenerate.addActionListener(this);
    constraints.gridx = 1;
    constraints.gridy = 2;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 0;
    constraints.weighty = 0;
    constraints.fill = GridBagConstraints.NONE;
    constraints.anchor = GridBagConstraints.SOUTHEAST;
    constraints.insets = new Insets(0, 5, 5, 5);
    panel.add(this.bGenerate, constraints);

    return panel;
  }



  /**
   * Handle the action events.
   * 
   * @param event
   *          The action event.
   */
  public void actionPerformed(final ActionEvent event)
  {

    File xmi = this.mainPanel.getXMIFile();
    final File output = this.mainPanel.getOutputFolder();
    if (xmi == null) {
      JOptionPane.showMessageDialog(this, "Please select a XMI File/xargo file.", "DAO Generation", JOptionPane.ERROR_MESSAGE);
    }
    else if (output == null) {
      JOptionPane.showMessageDialog(this, "Please select an output folder.", "DAO Generation", JOptionPane.ERROR_MESSAGE);
    }
    else {
      try {

        if (xmi.getName().endsWith(".zargo")) {
          xmi = getUmlGeneratorManager().getXmiFileFromArgoFile(xmi);
        }

        // Delete the content of the output folder.
        if (JOptionPane.showConfirmDialog(this, "Do you want to erase the content of the output folder?\n" + output.getAbsolutePath(), "Output content deletion", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
          this.deleteFolderContent(output);
        }

        final GenerationConfigurationImpl configuration = new GenerationConfigurationImpl();
        configuration.setXmiFiles(new File[] { xmi });
        configuration.setSrcDir(new File(output, "/src/main/java"));
        configuration.setResourcesDir(new File(output, "/src/main/resources"));
        configuration.setGeneratedSrcDir(new File(output, "/src/main/java-generated"));
        configuration.setGeneratedResourcesDir(new File(output, "/src/main/resources-generated"));
        configuration.setJalopyConfiguration(new URL("http://maven.1genia:81/config/jalopy/toolbox-jalopy.xml"));
        configuration.setConfigurationPackage("com.genia.toolbox.uml_generator.test.plugin");
        configuration.setLocales(new String[] { "fr" });

        getUmlGeneratorManager().generateModele(configuration);

        JOptionPane.showMessageDialog(this, "Done !", "DAO Generation", JOptionPane.INFORMATION_MESSAGE);

      }
      catch (final Exception e) {
        JOptionPane.showMessageDialog(this, "The DAO could not be generated\nPlease check your model.", "DAO Generation", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
      }
    }
  }



  /**
   * Delete the folder content.
   * 
   * @param folder
   *          The folder.
   */
  private void deleteFolderContent(final File folder)
  {
    if (folder != null && folder.isDirectory()) {
      final File[] childs = folder.listFiles();
      if (childs != null) {
        for (final File element : childs) {
          this.deleteFile(element);
        }
      }
    }
  }



  /**
   * Delete the file or the folder with its content.
   * 
   * @param file
   *          The file or folder.
   */
  private void deleteFile(final File file)
  {
    if (file != null) {
      if (file.isDirectory()) {
        final File[] childs = file.listFiles();
        if (childs != null) {
          for (final File element : childs) {
            this.deleteFile(element);
          }
        }
        file.delete();
      }
      else {
        file.delete();
      }
    }
  }



  /**
   * getter for the umlGeneratorManager property.
   * 
   * @return the umlGeneratorManager
   */
  public UmlGeneratorManager getUmlGeneratorManager()
  {
    return umlGeneratorManager;
  }



  /**
   * setter for the umlGeneratorManager property.
   * 
   * @param umlGeneratorManager
   *          the umlGeneratorManager to set
   */
  public void setUmlGeneratorManager(final UmlGeneratorManager umlGeneratorManager)
  {
    this.umlGeneratorManager = umlGeneratorManager;
  }

}
